package com.stox.ui.javafx.list.widget.menu.item;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import com.stox.dto.AbstractModel;
import com.stox.dto.WatchList;
import com.stox.ui.javafx.list.client.WatchListClient;
import com.stox.ui.javafx.list.widget.menu.WatchListContextMenu;

@Component
public class ClearEntriesMenuItem extends MenuItem implements InitializingBean,
		EventHandler<ActionEvent> {

	@Autowired
	private ApplicationContext applicationContext;
	
	@Autowired
	private WatchListClient watchListClient;
	
	public ClearEntriesMenuItem() {
		setOnAction(this);
	}
	
	@Override
	public void afterPropertiesSet() throws Exception {
		setText(applicationContext.getMessage("ClearEntries", null, Locale.getDefault()));
	}

	@Override
	public void handle(ActionEvent arg0) {
		WatchListContextMenu watchListContextMenu = (WatchListContextMenu)getParentPopup(); 
		TreeView<AbstractModel> treeView = watchListContextMenu.getTreeView();
		TreeItem<AbstractModel> treeItem = treeView.getSelectionModel().getSelectedItem();
		if(null != treeItem && null != treeItem.getValue()){
			watchListClient.deleteEntriesByParentId(treeItem.getValue().getId());
			List<TreeItem<AbstractModel>> removableChildren = new ArrayList<TreeItem<AbstractModel>>();
			for(TreeItem<AbstractModel> child : treeItem.getChildren()){
				if(null != child && null != child.getValue() && !(child.getValue() instanceof WatchList)){
					removableChildren.add(child);
				}
			}
			treeItem.getChildren().removeAll(removableChildren);
		}
	}
	
}
